﻿using System;
using System.Globalization;

namespace Ewk.Runtime.Serialization.CharacterSeparated
{
    class CharacterSeparatedInt32Serializer : DatafieldSerializer<CharacterSeparatedDatafieldAttribute>
    {
        public override string Serialize(object datafield, CharacterSeparatedDatafieldAttribute datafieldAttribute)
        {
            var value = (int) datafield;
            return value.ToString(datafieldAttribute.Format, CultureInfo.CurrentCulture);
        }

        public override object Deserialize(string datafield, CharacterSeparatedDatafieldAttribute datafieldAttribute)
        {
            if (string.IsNullOrEmpty(datafield))
            {
                return default(int);
            }

            int result;
            if (int.TryParse(datafield, out result))
            {
                return result;
            }

            var exceptionMessage = string.Format(CultureInfo.CurrentCulture, ExceptionMessages.CannotDeserializeValue, datafield, DatafieldType);
            OnDatafieldSerializationFailed(exceptionMessage);

            return default(int);
        }

        public override Type DatafieldType
        {
            get { return typeof(int); }
        }
    }
}
